<template>
  <div class="order-management-container">
    <el-page-header 
      @back="handleBack" 
      content="订单管理"
      class="page-header"
    />
    
    <!-- 订单列表 -->
    <el-card class="order-card">
      <template #header>
        <div class="header-operation">
          <span>订单列表</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-loading :visible="loading" text="加载中..."></el-loading>
      </div>
      
      <div v-else-if="data.list.length === 0" class="empty-state">
        <el-empty description="暂无订单数据"></el-empty>
      </div>
      
      <div v-else class="order-list">
        <!-- 订单项 -->
        <el-collapse v-model="activeNames" class="order-collapse">
          <el-collapse-item 
            :name="order.order_id" 
            v-for="order in data.list" 
            :key="order.order_id"
          >
            <template #title>
              <div class="order-header">
                <div class="order-info">
                  <span class="order-status" :class="getStatusClass(order.status)">
                    {{ getStatusText(order.status) }}
                  </span>
                  <span class="order-id">订单编号: {{ order.order_id }}</span>
                </div>
                <div class="order-date">送达时间: {{ order.send_time }}</div>
              </div>
            </template>
            
            <!-- 订单商品 -->
            <div class="order-goods">
              <el-table 
                :data="order.flowers" 
                border 
                :show-header="false"
                class="goods-table"
                @row-click="openModal"
              >
                <el-table-column prop="image" width="100">
                  <template #default="scope">
                    <el-image 
                      :src="scope.row.image" 
                      :alt="scope.row.name"
                      fit="cover"
                      class="flower-image"
                    ></el-image>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template #default="scope">
                    <div class="flower-info">
                      <div class="flower-name">{{ scope.row.name }}</div>
                      <div class="flower-detail">
                        <span>用途: {{ scope.row.use }}</span>
                        <span>材质: {{ scope.row.material }}</span>
                        <span>类别: {{ scope.row.category }}</span>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="80" align="center">
                  <template #default="scope">
                    ×{{ order.counts[scope.$index] }}
                  </template>
                </el-table-column>
                <el-table-column width="100" align="right">
                  <template #default="scope">
                    ¥{{ scope.row.price.toFixed(2) }}
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 订单总额 -->
              <div class="order-total">
                订单总额: 
                <span class="total-price">
                  ¥{{ calculateTotal(order).toFixed(2) }}
                </span>
              </div>
            </div>
            
            <!-- 订单信息编辑 -->
            <div class="order-detail">
              <el-form 
                :model="order" 
                label-width="100px"
                class="order-form"
              >
                <el-form-item label="收货地址">
                  <el-input 
                    v-model="order.address" 
                    placeholder="请输入收货地址"
                    class="edit-input"
                  ></el-input>
                </el-form-item>
                
                <el-form-item label="送达时间">
                  <el-date-picker
                    v-model="order.send_time"
                    type="datetime"
                    placeholder="选择送达时间"
                    format="YYYY.MM.DD HH:mm"
                    value-format="YYYY.MM.DD HH:mm"
                    class="edit-picker"
                  ></el-date-picker>
                </el-form-item>
                
                <el-form-item label="订单留言">
                  <el-input
                    v-model="order.note"
                    type="textarea"
                    placeholder="请输入留言内容"
                    :rows="3"
                    class="edit-textarea"
                  ></el-input>
                </el-form-item>
                
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="saveOrderChanges(order)"
                    class="save-btn"
                    v-if="order.status==0"
                  >
                    保存修改
                  </el-button>
                  <el-button 
                    type="danger" 
                    @click="cancelOrder(order.order_id)"
                    class="save-btn"
                    v-if="order.status==0"
                  >
                    取消订单
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      
      <!-- 分页 -->
      <div v-if="data.total > 0" class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="data.pageNum"
          :page-sizes="[1, 2, 3, 5]"
          :page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
        ></el-pagination>
      </div>
    </el-card>
  </div>


  <!-- 花卉信息弹窗 -->
  <el-dialog 
      v-model="dialogVisible" 
      title="花卉详情" 
      :width="dialogWidth"
      :before-close="handleClose"
    >
      <div class="flower-detail">
        <!-- 花卉图片 -->
        <div class="flower-image2">
          <el-image 
            :src="flowerData.image" 
            :alt="flowerData.name"
            fit="contain"
          ></el-image>
        </div>
        
        <!-- 花卉信息 -->
        <div class="flower-info2">
          <el-descriptions column="1" border>
            <el-descriptions-item label="花卉ID">{{ flowerData.flowerId }}</el-descriptions-item>
            <el-descriptions-item label="名称">{{ flowerData.name }}</el-descriptions-item>
            <el-descriptions-item label="用途">{{ flowerData.use }}</el-descriptions-item>
            <el-descriptions-item label="花材">{{ flowerData.material }}</el-descriptions-item>
            <el-descriptions-item label="类别">{{ flowerData.category }}</el-descriptions-item>
            <el-descriptions-item label="数量">{{ flowerData.count }} 枝</el-descriptions-item>
            <el-descriptions-item label="价格">¥{{ flowerData.price.toFixed(2) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>



</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

// 状态管理
const loading = ref(true);
const activeNames = ref([]);
const data = ref({
  total: 0,
  pageSize: 3,
  list: [],
  pageNum: 1
});

// 模拟后端数据
const mockData = {
  "code": "200",
  "msg": "查询成功",
  "data": {
    "total": 4,
    "pageSize": 3,
    "list": [
      {
        "order_id": "999",
        "user_id": 4,
        "flowers": [
          {
            "flowerId": 78,
            "name": "哀思鲜花_康乃馨_其他_11枝_078",
            "use": "哀思鲜花",
            "material": "康乃馨",
            "category": "其他",
            "count": 2,
            "price": 57.0,
            "image": "https://flower-java.oss-cn-beijing.aliyuncs.com/flower_image/flower%20%283%29.jpg"
          },
          {
            "flowerId": 79,
            "name": "探病问候_玫瑰_周花_52枝_079",
            "use": "探病问候",
            "material": "玫瑰",
            "category": "周花",
            "count": 4,
            "price": 154.0,
            "image": "https://flower-java.oss-cn-beijing.aliyuncs.com/flower_image/flower%20%283%29.png"
          },
          {
            "flowerId": 80,
            "name": "商务鲜花_菊花_礼盒_11枝_080",
            "use": "商务鲜花",
            "material": "菊花",
            "category": "礼盒",
            "count": 6,
            "price": 42.0,
            "image": "https://flower-java.oss-cn-beijing.aliyuncs.com/flower_image/flower%20%2830%29.jpg"
          }
        ],
        "counts": [11, 52],
        "address": "南苑3号楼213宿舍",
        "send_time": "2025.09.20 20:00",
        "note": "请按时送达，谢谢",
        "status": 0
      },
      {
        "order_id": "1000",
        "user_id": 5,
        "flowers": [
          {
            "flowerId": 81,
            "name": "生日鲜花_百合_花束_19枝_081",
            "use": "生日鲜花",
            "material": "百合",
            "category": "花束",
            "count": 1,
            "price": 128.0,
            "image": "https://flower-java.oss-cn-beijing.aliyuncs.com/flower_image/flower%20%2815%29.jpg"
          }
        ],
        "counts": [19],
        "address": "北苑1号楼502室",
        "send_time": "2025.10.15 14:30",
        "note": "请包装精美一些，生日用",
        "status": 1
      },
      {
        "order_id": "1001",
        "user_id": 2,
        "flowers": [
          {
            "flowerId": 82,
            "name": "爱情鲜花_红玫瑰_礼盒_99枝_082",
            "use": "爱情鲜花",
            "material": "红玫瑰",
            "category": "礼盒",
            "count": 1,
            "price": 399.0,
            "image": "https://flower-java.oss-cn-beijing.aliyuncs.com/flower_image/flower%20%2822%29.jpg"
          }
        ],
        "counts": [99],
        "address": "东苑5号楼307",
        "send_time": "2025.11.11 18:00",
        "note": "双十一惊喜，提前送达",
        "status": 2
      }
    ],
    "pageNum": 1
  }
};

// 页面加载时获取订单数据
onMounted(() => {
  fetchOrders();
});
import axios from '@/http/axios'

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true;

  
  var res = await axios.get('/order/list/'+data.value.pageNum+'/'+data.value.pageSize)

  data.value = res.data.data

  // 默认展开第一个订单
  if (data.value.list.length > 0) {
      activeNames.value = [data.value.list[0].order_id];
    }

  loading.value = false
};

// 计算订单总额
const calculateTotal = (order) => {
  var sum = 0
  for(var i = 0;i<order.flowers.length;i++){
    sum += order.flowers[i].price * order.counts[i]
  }
  return sum
};

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已支付',
    1: '已完成',
    2: '已取消',
  };
  return statusMap[status] || '未知状态';
};

// 获取订单状态样式
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-paid',
    1: 'status-pending',
    2: 'status-canceled',
    3: 'status-completed',
    4: 'status-canceled'
  };
  return classMap[status] || '';
};

// 保存订单修改
const saveOrderChanges = async (order) => {

  loading.value = true;
  var res = await axios.put('/order/update',order)
  if(res.data.code == 200){
    ElMessage.success("修改成功")
    fetchOrders()
  }else{
    ElMessage.error(res.data.msg)
  }
};
const cancelOrder = async (orderId) => {
  loading.value = true;
  var res = await axios.delete('/order/'+orderId)
  if(res.data.code == 200){
    ElMessage.success("取消成功")
    fetchOrders()
  }else{
    ElMessage.error(res.data.msg)
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  data.value.pageSize = val;
  data.value.pageNum = 1;
  fetchOrders();
};

const handleCurrentChange = (val) => {
  data.value.pageNum = val;
  fetchOrders();
};

import { useRouter } from 'vue-router';
const router = useRouter()
// 返回按钮处理
const handleBack = () => {
  ElMessage.info('返回上一页');
  router.back()
};


// 控制弹窗显示与隐藏
const dialogVisible = ref(false);

// 弹窗宽度
const dialogWidth = '600px';

// 花卉信息数据
const flowerData = ref({
  "flowerId": 80,
  "name": "商务鲜花_菊花_礼盒_11枝_080",
  "use": "商务鲜花",
  "material": "菊花",
  "category": "礼盒",
  "count": 6,
  "price": 42.0,
  "image": "https://flower-java.oss-cn-beijing.aliyuncs.com/flower_image/flower%20%2830%29.jpg"
});

// 打开弹窗
const openModal = (row) => {
  console.log(row)
  flowerData.value = row
  dialogVisible.value = true;
};

// 关闭弹窗的回调
const handleClose = (done) => {
  done();
};
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.order-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.header-operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.order-collapse {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.order-info {
  display: flex;
  gap: 16px;
}

.order-id {
  font-weight: 500;
}

.order-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.status-pending {
  background-color: #e6a23c;
}

.status-paid {
  background-color: #409eff;
}

.status-shipped {
  background-color: #67c23a;
}

.status-completed {
  background-color: #1989fa;
}

.status-canceled {
  background-color: #f56c6c;
}

.order-date {
  color: #606266;
  font-size: 14px;
}

.order-goods {
  margin: 16px 0;
}

.goods-table {
  width: 100%;
  margin-bottom: 16px;
}

.flower-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.flower-info {
  padding: 8px 0;
}

.flower-name {
  margin-bottom: 8px;
  font-weight: 500;
}

.flower-detail {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  color: #606266;
  font-size: 12px;
}

.order-total {
  text-align: right;
  padding: 12px;
  border-top: 1px dashed #ebeef5;
  font-size: 16px;
}

.total-price {
  color: #f56c6c;
  font-weight: bold;
  margin-left: 8px;
}

.order-detail {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
}

.order-form {
  max-width: 800px;
}

.edit-input, .edit-picker, .edit-textarea {
  width: 100%;
  max-width: 500px;
}

.save-btn {
  margin-top: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-management-container {
    padding: 10px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .flower-detail {
    flex-direction: column;
    gap: 4px;
  }
  
  .order-total {
    font-size: 14px;
  }
}
.flower-info-container {
  padding: 20px;
}

.show-modal-btn {
  margin: 10px;
}

.flower-detail {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.flower-image2 {
  width: 200px;
  height: 200px;
  flex-shrink: 0;
}

.flower-info2 {
  flex-grow: 1;
  min-width: 300px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style>
    